<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <label style="margin-right: 5px">分类名称：</label>
        <el-input v-model="name" placeholder="请输入分类名称：" style="width: 15%" clearable @clear="getCategoryPage"
          @keyup.enter="getCategoryPage" />
        <label style="margin: 0 10px">分类类型：</label>
        <el-select v-model="categoryType" placeholder="请选择" clearable style="width: 15%" @clear="getCategoryPage">
          <el-option v-for="item in option" :key="item.type" :label="item.value" :value="item.type" />
        </el-select>
        <el-button type="primary" style="margin-left: 10px" @click="getCategoryPage">查询</el-button>
        <div style="float: right" v-if="userStore.rule !== 'admin'">
          <el-button type="primary" class="continue" @click="addHandle('dish')"> 新增菜品分类 </el-button>
          <el-button type="primary" style="margin-left: 20px" @click="addHandle('meal')"> 新增套餐分类 </el-button>
        </div>
      </div>
    </template>
    <el-table :data="categorys" style="width: 100%">
      <el-table-column prop="businessName" label="商家" />
      <el-table-column prop="name" label="分类名称" />
      <el-table-column prop="type" label="分类类型">
        <template #default="{ row }">
          <span>{{ row.type == 1 ? '菜品分类' : '套餐分类' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template #default="{ row }">
          <div class="status" :class="{ 'stop-status': row.status === 0 }">
            {{ row.status === 0 ? '禁用' : '启用' }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="操作时间" />
      <el-table-column label="操作" width="240" align="center">
        <template #default="{ row }" v-if="userStore.rule === 'admin'">
          <el-button size="small" @click="statusHandle(row)" :type="row.status == 1 ? 'danger' : 'success'">
            {{ row.status == 1 ? '禁用' : '启用' }}
          </el-button>
        </template>
        <template #default="{ row }" v-else>
          <el-button size="small" @click="updateHandle(row)"> 修改 </el-button>
          <el-button size="small" @click="deleteCategory(row)"> 删除 </el-button>
          <el-button size="small" @click="statusHandle(row)" :type="row.status == 1 ? 'danger' : 'success'">
            {{ row.status == 1 ? '禁用' : '启用' }}
          </el-button>
        </template>
      </el-table-column>
       <template #empty>
         <el-empty />
      </template>
    </el-table>
    <template #footer>
      <!-- 分页条 -->
      <Pagination :page="page" :pageSize="pageSize" :total="total" @onSizeChange="onSizeChange"
        @onPageChange="onPageChange" />
    </template>
    <!-- 添加分类弹窗 -->
    <el-dialog v-model="dialogVisible" :title="title" width="500" :show-close="false">
      <el-form :model="categoryForm" label-width="100px" :rules="rules" ref="categoryFormRef">
        <el-form-item label="分类名称：" prop="name">
          <el-input v-model="categoryForm.name" placeholder="请输入分类名称" maxlength="20" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitHandle">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>
<script setup lang="ts">
import Pagination from '@/components/Pagination/index.vue'
import {
  addCategoryAPI,
  deleteCategoryAPI,
  getCategoryPageAPI,
  postCategoryStatusAPI,
  putCategoryAPI,
} from '@/api/business/category'
import { CategoryResult } from '@/types/category'
import { ElForm, ElMessage, ElMessageBox, FormRules } from 'element-plus'
import { ref, onMounted, reactive } from 'vue'
import { useUserStore } from '@/stores/userStore'
import { getAdminCategoryPageAPI, postAdminCategoryStatusAPI } from '@/api/admin/category'
const userStore = useUserStore()
onMounted(() => {
  getCategoryPage()
})
//当每页条数发生了变化，调用此函数
const onSizeChange = (num: number) => {
  pageSize.value = num
  getCategoryPage()
}
//当前页码发生变化，调用此函数
const onPageChange = (num: number) => {
  page.value = num
  getCategoryPage()
}

// 分类类型：1为菜品分类，2为套餐分类
const option = [
  {
    type: 1,
    value: '菜品分类',
  },
  {
    type: 2,
    value: '套餐分类',
  },
]
// 分类名称
const name = ref('')
const categoryType = ref<number>()
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
// 分类数据
const categorys = ref<CategoryResult[]>([])
const getCategoryPage = async () => {
  let params = {
    page: page.value,
    pageSize: pageSize.value,
    businessId: userStore.rule === 'admin' ? undefined : userStore.user.id,
    name: name.value || undefined,
    type: categoryType.value || undefined,
  }
  try {
    if (userStore.rule === 'admin') {
      let { data } = await getAdminCategoryPageAPI(params)
      categorys.value = data.records
      total.value = data.total
    } else {
      let { data } = await getCategoryPageAPI(params)
      categorys.value = data.records
      total.value = data.total
    }
  } catch (error) {
    console.log(error)
  }
}
// 启用、禁用分类
const statusHandle = async (row: any) => {
  const id = row.id
  const status = row.status
  ElMessageBox.confirm('确认要执行此操作吗?', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      if (userStore.rule === 'admin') {
        await postAdminCategoryStatusAPI(!status ? 1 : 0, id)
        getCategoryPage()
      } else {
        await postCategoryStatusAPI(!status ? 1 : 0, id)
        getCategoryPage()
      }
      ElMessage.success('修改成功')
    })
    .catch(() => {
      ElMessage.info('已取消')
    })
}
// 表单校验
const rules = reactive<FormRules<typeof categoryForm>>({
  name: [
    {
      required: true,
      trigger: 'blur',
      validator: (_rule: any, value: string, callback: (error?: Error) => void) => {
        // const reg = /[\u4e00-\u9fa5]/
        var reg = new RegExp('^[A-Za-z\u4e00-\u9fa5]+$')
        if (!value) {
          callback(new Error(title.value + '不能为空'))
        } else if (value.length < 2) {
          callback(new Error('分类名称输入不符，请输入2-20个字符'))
        } else if (!reg.test(value)) {
          callback(new Error('分类名称包含特殊字符'))
        } else {
          callback()
        }
      },
    },
  ],
})
// 添加/修改分类弹窗
const dialogVisible = ref(false)
const action = ref('')
const title = ref('')
// 分类表单
const categoryForm = ref({} as CategoryResult)
// 添加分类
const addHandle = (value: string) => {
  if (value === 'dish') {
    title.value = '添加菜品分类'
    categoryForm.value.type = 1
  } else if (value === 'meal') {
    title.value = '添加套餐分类'
    categoryForm.value.type = 2
  }
  action.value = 'add'
  categoryForm.value.name = ''
  dialogVisible.value = true
}
// 修改分类
const updateHandle = (row: CategoryResult) => {
  title.value = '修改分类'
  action.value = 'update'
  categoryForm.value.id = row.id
  categoryForm.value.name = row.name
  categoryForm.value.type = row.type
  dialogVisible.value = true
  console.log(categoryForm.value)
}
const categoryFormRef = ref<InstanceType<typeof ElForm> | null>(null)

// 确认提交
const submitHandle = () => {
  if (action.value === 'add' && categoryForm.value) {
    categoryFormRef.value?.validate(async (vaild: boolean) => {
      if (vaild) {
        let params = {
          name: categoryForm.value.name,
          type: categoryForm.value.type,
        }
        await addCategoryAPI(params)
        ElMessage.success('添加成功!')
        dialogVisible.value = false
        getCategoryPage()
      } else {
        ElMessage.error('表单校验失败')
      }
    })
  } else if (action.value === 'update' && categoryForm.value) {
    categoryFormRef.value?.validate(async (vaild: boolean) => {
      if (vaild) {
        await putCategoryAPI({
          id: categoryForm.value.id,
          name: categoryForm.value.name,
          type: categoryForm.value.type,
        })
        ElMessage.success('修改成功!')
        dialogVisible.value = false
        getCategoryPage()
      } else {
        ElMessage.error('表单校验失败')
      }
    })
  }
}
// 删除分类
const deleteCategory = (row: CategoryResult) => {
  if (row && row.status !== 1) {
    ElMessageBox.confirm('确认要删除该菜品吗?', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      await deleteCategoryAPI(row.id)
      getCategoryPage()
    })
  } else {
    ElMessage.warning('启用中的分类不能删除' + (row ? '' : '（无效的删除对象）'))
  }
}
</script>
<style scoped>
.header {
  align-items: space-around;
}
</style>
